<template>
  <div v-if="permissionsLists(43)">
    <page-header
      :title="$t('m.Menu_Device_PowerBank')"
      :has-return="false"
    >
      <el-button
        type="primary"
        @click="exportBtn"
        v-if="userType == 1 && permissionsLists(179)"
      >
        {{ $t('m.Import_Power_Bank') }}
      </el-button>
    </page-header>
    <div class="container">
      <div class="list_div">
        <div class="page_list_div">
          <el-form class="page_list_top" label-position="right">
            <el-form-item :label="$t('m.search_') + ':'" class="page_list_top">
              <el-input
                :placeholder="
                  $t('m.Order_List_Powerbank') + ' / ' + $t('m.Station_SN')
                "
                prefix-icon="el-icon-search"
                style="width:200px;"
                clearable
                v-model="params.search"
              />
            </el-form-item>
            <el-form-item
              :label="$t('m.branch_Creationdate') + ':'"
              class="page_list_top"
            >
              <el-date-picker
                style="width:246px;"
                v-model="params.rangeTime"
                :picker-options="datePickerOptions"
                :default-value="timeDefaultShow"
                type="daterange"
                :default-time="['00:00:00', '23:59:59']"
                value-format="timestamp"
                range-separator="~"
                :start-placeholder="$t('m.start_date')"
                :end-placeholder="$t('m.end_date')"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item :label="$t('m.status') + ':'" class="page_list_top">
              <el-select
                v-model="params.state"
                ref="select1"
                @change="searchClick('', 1)"
              >
                <el-option
                  v-for="item in options1"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('m.Abnormal_warning') + ':'"
              class="page_list_top"
            >
              <el-select
                v-model="params.isAbnormal"
                ref="select2"
                @change="searchClick('', 2)"
              >
                <el-option
                  v-for="item in options2"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="page_list_top page_list_search">
              <el-button
                class="search_button reset_button"
                @click="searchClick('')"
                >{{ $t('m.search_') }}</el-button
              >
            </el-form-item>
            <el-form-item class="page_list_top page_list_search">
              <el-button class="reset_button" @click="searchClick('1')">{{
                $t('m.refresh')
              }}</el-button>
            </el-form-item>
            <el-form-item class="page_list_top " v-if="permissionsLists(242)">
              <el-button class="reset_button" @click="exportPower">{{
                $t('m.exports')
              }}</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-divider class="el_divider"></el-divider>
        <div class="el_table_div">
          <el-table :data="page.records" key="0">
            <el-table-column
              fixed
              prop="pbNo"
              :label="$t('m.Order_List_Powerbank')"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="bc"
              :label="$t('m.Order_Battery_LevelR')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.bc }}%</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="useNum"
              :label="$t('m.Station_Usage_frequency')"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="cumulativeChargeCount"
              :label="$t('m.Accumulated_charging')"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="cabinetNo"
              :label="$t('m.Station_Station_ID')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.cabinetNo | strFormat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="damageNum"
              :label="$t('m.Station_Faulty')"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="lastUser"
              :label="$t('m.Station_Faulty_User')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.lastUser | strFormat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="isAbnormal"
              :label="$t('m.Station_Exceptional')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.isAbnormal | stateFormat(options2) }}
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column
              :label="$t('m.Warning_information')"
              min-width="150"
            >
              <template slot-scope="scope">
                <div v-if="scope.row.isAbnormal == 0">
                  {{ scope.row.isAbnormal | stateFormat(options2) }}
                </div>
                <span v-else>
                  {{
                    scope.row.isAbnormalCellCurrent == 1
                      ? '机芯电流异常' + '、'
                      : ''
                  }}{{
                    scope.row.isAbnormalCellVoltage == 1
                      ? '机芯电压异常' + '、'
                      : ''
                  }}{{
                    scope.row.isAbnormalChargeCurrent == 1
                      ? '充电电流异常' + '、'
                      : ''
                  }}{{
                    scope.row.isAbnormalChargeVoltage == 1
                      ? '充电电压异常' + '、'
                      : ''
                  }}{{ scope.row.isOverCharge == 1 ? '过量充电异常' + '、' : ''
                  }}{{ scope.row.isOverTemperature == 1 ? '温度异常' : '' }}
                </span>
              </template>
            </el-table-column> -->
            <el-table-column
              prop="state"
              :label="$t('m.status')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.state | stateFormat(options1) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              :label="$t('m.branch_Creationdate')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.createTime | dateformat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              :label="$t('m.Users_Details_Operation')"
              min-width="104"
              v-if="isArrayEqual([44, 180, 181, 182], permissionsLists)"
            >
              <template slot-scope="scope">
                <el-dropdown placement="bottom">
                  <img
                    src="@/assets/imgs/ic_operation.svg"
                    alt=""
                    class="dropdown_img"
                  />
                  <el-dropdown-menu
                    slot="dropdown"
                    style="white-space: nowrap !important;"
                  >
                    <el-dropdown-item
                      @click.native="detailClick(scope.row)"
                      v-if="permissionsLists(44)"
                      >{{ $t('m.Details') }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="dialogClick(3, scope.row)"
                      v-if="scope.row.state != 4 && permissionsLists(180)"
                      :disabled="scope.row.state == 6 || !scope.row.cabinetNo"
                      >{{ $t('m.Station_eject') }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="dialogClick(1, scope.row)"
                      :disabled="scope.row.state == 6 || !scope.row.cabinetNo"
                      v-if="permissionsLists(181)"
                      >{{ $t('m.Station_refreshBattery') }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="dialogClick(2, scope.row)"
                      v-if="permissionsLists(182)"
                      :disabled="
                        scope.row.state == 0 ||
                          scope.row.state == 1 ||
                          scope.row.state == 6
                      "
                      >{{ $t('m.initialize') }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
            <emptydata
              slot="empty"
              v-if="!page.records || page.records.length == 0"
            />
          </el-table>
          <el-pagination
            background
            :page-sizes="[10, 20, 30, 40, 50]"
            :page-size="page.size"
            :current-page.sync="page.current"
            layout="total, sizes, prev, pager, next, jumper"
            :pager-count="5"
            :total="page.total"
            class="el_pagination"
            @size-change="changePageSize"
            @current-change="changePageNum"
            v-show="page.total > 0"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 充电宝刷新/恢复/弹出 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="operateDialog"
      :title="dialogType | stateFormat(optionsTitle)"
      width="520px"
      top="200px"
      append-to-body
    >
      <div class="dialog_content">
        <div class="dialog_content1">
          {{ dialogType | stateFormat(optionsText) }}
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="operateDialog = false" class="cancel_btn">{{
          $t('m.cancel')
        }}</el-button>
        <el-button @click="changePower" class="cancel_btn confirm_btn">{{
          $t('m.confirm_')
        }}</el-button>
      </span>
    </el-dialog>

    <!-- 导入充电宝 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="exportDialog"
      :title="$t('m.Import_Power_Bank')"
      width="520px"
      top="200px"
      append-to-body
    >
      <div class="dialog_content">
        <div
          class="dialog_content1"
          style="display: flex; align-items: center;justify-content: center;"
        >
          <el-upload
            action="/manage/excel/power-banks"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-change="handleChange"
            :headers="platformId"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :file-list="fileList"
          >
            <el-button class="upload_btn">
              {{ $t('m.clickUpload') }}
            </el-button>
          </el-upload>
        </div>
        <div
          class="dialog_content1"
          @click="exportExcel"
          style="display: flex; align-items: center;justify-content: center;color:var(--text-color);cursor: pointer;"
        >
          {{ $t('m.downloadTemplate') }}
        </div>
        <div
          class="dialog_content1"
          v-if="showResult"
          style="display: flex; align-items: center;justify-content: center;"
        >
          <img
            src="@/assets/imgs/payment_ic_success@2x.png"
            alt=""
            width="14px"
            style="margin-right:8px"
          />{{ $t('m.Import_success') }}:{{ result.succCount }}
        </div>
        <div
          class="dialog_content1"
          v-if="showResult"
          style="display: flex; align-items: center;justify-content: center;"
        >
          <img
            src="@/assets/imgs/payment_ic_fail@2x.png"
            alt=""
            width="14px"
            style="margin-right:8px"
          />{{ $t('m.Import_failure') }}:{{ result.errCount }}
        </div>
      </div>
      <div class="dialog_content" v-if="showResult">
        <div class="el_table_div" style="padding:0;">
          <el-table
            :data="
              result.failedList.slice(
                (tbPage.currentPage - 1) * tbPage.pagesize,
                tbPage.currentPage * tbPage.pagesize
              )
            "
            border
          >
            <el-table-column
              prop="pbNo"
              :label="$t('m.Order_List_Powerbank')"
              min-width="80"
            >
            </el-table-column>
            <el-table-column
              prop="remark"
              :label="$t('m.Station_Add_reason')"
              min-width="160"
            >
            </el-table-column>
          </el-table>
          <el-pagination
            background
            :page-sizes="[5]"
            :page-size="5"
            :current-page.sync="tbPage.currentPage"
            layout=" prev, pager, next"
            :pager-count="5"
            :total="result.failedList.length"
            style="margin-right:-5px;"
            class="el_pagination"
            v-show="result.failedList.length > 0"
          >
          </el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import page from '@/mixins/page'
export default {
  mixins: [page],
  data () {
    return {
      datePickerOptions: {
        disabledDate (time) {
          let current_time = new Date().Format('yyyy-MM-dd') + ' 23:59:59' //时间日期为：‘当前日期 23:59:59’
          let t = new Date(current_time).getTime() //‘当前日期 23:59:59’的时间戳
          return time.getTime() > t
        }
      },
      params: {
        search: '', //模糊查询
        rangeTime: '', //时间戳范围
        state: '', // 状态：0-可用 1-租借中 2-已损坏 3-报失(包括已购买的充电宝) 4-强制弹出 5-已出售
        isAbnormal: '',
        cabinetType:''
      },
      options1: [
        {
          value: '',
          label: this.$t('m.all')
        },
        {
          value: 0,
          label: this.$t('m.Station_untapped')
        },
        {
          value: 1,
          label: this.$t('m.Order_Status_Renting')
        },
        {
          value: 2,
          label: this.$t('m.Station_Damaged')
        },
        // {
        //   value: 3,
        //   label: '已报失'
        // },
        {
          value: 4,
          label: this.$t('m.Station_eject2')
        },
        {
          value: 5,
          label: this.$t('m.Station_Sold')
        },
        {
          value: 6,
          label: this.$t('m.Inventory')
        }
      ],
      options2: [
        {
          value: '',
          label: this.$t('m.all')
        },
        {
          value: 1,
          label: this.$t('m.Station_List_Distribution_Yes')
        },
        {
          value: 0,
          label: this.$t('m.Station_List_Distribution_No')
        }
      ],
      optionsTitle: [
        {
          value: 1,
          label: this.$t('m.Station_refreshBattery')
        },
        {
          value: 2,
          label: this.$t('m.initialize')
        },
        {
          value: 3,
          label: this.$t('m.Station_eject')
        }
      ],
      optionsText: [
        {
          value: 1,
          label: this.$t('m.Station_Confirm_to')
        },
        {
          value: 2,
          label: this.$t('m.Station_reactivate_power')
        },
        {
          value: 3,
          label: this.$t('m.Station_eject_power_bank')
        }
      ],
      tableData: [],
      operateDialog: false, //充电宝刷新/恢复/弹出
      exportDialog: false, //导入机柜弹出
      fileList: [], //上传的文件
      stationRow: '', //选中机柜
      platformId: {
        'lang-key': 'Import_Power_Bank',
        'platform-id': parseInt(sessionStorage.getItem('platformId')),
        add: this.$cache.getLang(),
        'brezze-language':
          this.$cache.getLang() == 'CN' ? 'ZH' : this.$cache.getLang()
      },
      result: {
        failedList: []
      }, //文件回调
      showResult: false, //显示文件结果列表
      tbPage: {
        currentPage: 1,
        pagesize: 5
      }, //文件页码
      dialogType: '',
      powerRow: '',
      userType: this.getUserType(), //用户类型
      permissionsIds: [] //权限id
    }
  },

  created () {
    this.$store.state.permissions.forEach(item => {
      this.permissionsIds.push(Number(this.$jsencrypt.decrypt(item)))
    })
    if (!this.permissionsLists(43)) {
      return
    }
    this.getPowerLists()
    this.timeDefaultShow = new Date()
    this.timeDefaultShow.setMonth(new Date().getMonth() - 1)
  },
  mounted () {},
  methods: {
    //权限id校验
    permissionsLists (val) {
      return this.permissionsIds.includes(val)
    },
    // 搜索/重置
    searchClick (reset, e) {
      // 是否重置
      let size = this.page.size
      this.page = this.$options.data.call(this).page
      if (reset) {
        this.params = this.$options.data.call(this).params
        this.timeDefaultShow = new Date()
        this.timeDefaultShow.setMonth(new Date().getMonth() - 1)
        this.remPageNum()
      } else {
        this.page.size = size
        this.setPageNum(this.page.current, this.page.size, this.params)
      }
      this.$nextTick(() => {
        e ? this.$refs[`select${e}`].blur() : ''
      })
      this.getPowerLists()
    },
    //获取机柜列表
    getPowerLists () {
      this.$api.equipment.getPowerList(this.params, this.page).then(res => {
        if (this.$ok(res)) {
          this.page = res.data
        }
      })
    },
    // 每页数
    changePageSize (val) {
      this.page.current = 1
      this.page.size = val
      this.getPowerLists()
    },
    // 当前页
    changePageNum (val) {
      this.page.current = val
      this.getPowerLists()
    },

    //充电宝详情
    detailClick (item) {
      this.setPageNum(this.page.current, this.page.size, this.params)
      this.$router.push({
        path: '/device/powerbank/detail',
        query: { id: item.id }
      })
    },
    //充电宝刷新/恢复/弹出
    dialogClick (e, item) {
      this.powerRow = item
      this.dialogType = e
      this.operateDialog = true
    },
    //修改充电宝状态
    changePower () {
      this.$openLoading()
      if (this.dialogType == 1) {
        this.refreshPower()
      } else if (this.dialogType == 2) {
        this.initializePower()
      } else {
        this.ejectPower()
      }
    },
    //操作按钮结果
    getRes (res) {
      if (this.$ok(res)) {
        this.$message.success(res.message)
        this.getPowerLists()
        this.operateDialog = false
        this.$closeLoading()
      } else {
        this.$message.error(res.message)
        this.$closeLoading()
      }
    },
    //刷新充电宝
    refreshPower () {
      let params = {
        cabinetNo: this.powerRow.cabinetNo
      }
      this.$api.equipment.refreshPower(params).then(res => {
        this.getRes(res)
      })
    },
    //恢复充电宝
    initializePower () {
      this.$api.equipment.initializePower(this.powerRow.id).then(res => {
        this.getRes(res)
      })
    },
    //弹出充电宝
    ejectPower () {
      let params = {
        cabinetNo: this.powerRow.cabinetNo,
        pos: this.powerRow.pos,
        powerBankId: this.powerRow.id
      }
      this.$api.equipment.ejectPower(params).then(res => {
        this.getRes(res)
      })
    },

    //导入充电宝
    exportBtn () {
      this.showResult = false
      this.result = { cabinetExcelDTO: [] }
      this.exportDialog = true
    },
    //下载模板
    exportExcel () {
      this.$openLoading()
      this.$api.equipment.getPowerTemplate().then(res => {
        window.downExcel(res)
        this.$closeLoading()
      })
    },
    beforeUpload (file) {
      const fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      const isFile = fileType === 'xls' || fileType === 'xlsx'
      if (!isFile) {
        this.$message.error(this.$t('m.Please_upload'))
        return false
      }
    },
    //导入回显
    handleChange (file, fileList) {
      var length = fileList.length
      var value = fileList[length - 1]
      var self = this
      if (value.response) {
        var code = value.response.code
        var res = value.response
        if (code == '0' && res.data != null) {
          self.showResult = true
          self.result = {
            failedList: res.data.failedList ? res.data.failedList : [],
            errCount: res.data.errCount ? res.data.errCount : '0',
            succCount: res.data.succCount ? res.data.succCount : '0'
          }
        } else {
          self.showResult = true
          self.result = {
            failedList: [],
            errCount: '0',
            succCount: '0'
          }
        }
        var type = code == '0' ? 'success' : 'error'
        if (code == '0') {
          this.getPowerLists()
        }            
        this.$message({
          // 弹框
          type: type,
          message: value.response.message
        })
      }
    },
    //导出列表
    exportPower () {
      this.$openLoading()
      this.$api.equipment.getExportPowerList(this.params).then(res => {
        window.downExcel(res, this.$t('m.Menu_Device_PowerBank'))
        this.$closeLoading()
      })
    }
  }
}
</script>
